import { SkillBase } from '@/assets/scripts/skill/SkillBase.js'
import { GameObject } from '@/assets/scripts/GameObject.js'

// 闪现技能
export class Flash extends SkillBase {
    constructor(player) {
        super(player, 15) // 15秒冷却时间
        this.player = player
        this.skillKey = 'f'
        this.skillName = 'flash'
        this.flashDistance = player.height * 0.3 // 闪现距离上限

        // 加载闪现技能图标
        this.load_icon('https://www.helloimg.com/i/2025/04/11/67f8a57d6ab75.png')
    }

    // 添加resize方法，更新闪现参数以匹配窗口大小变化
    resize() {
        // 更新闪现距离
        this.flashDistance = this.player.height * 0.3
    }

    // 施放技能 - 联机模式下只计算参数和显示效果，实际位移由服务器确定
    cast(tx, ty) {
        try {
            // 确保必要对象存在
            if (!this.player) {
                console.error("闪现技能错误: 玩家对象不存在");
                return false;
            }
            
            if (!this.player.gameMap) {
                console.error("闪现技能错误: 地图对象不存在");
                return false;
            }
            
            // 如果玩家死亡，不允许施放
            if (this.player.is_dead) {
                return false;
            }
            
            // 调用父类的cast方法检查冷却，如果在冷却中则返回失败
            if (!super.cast()) {
                return false;
            }

            // 计算闪现距离和角度
            let d = this.get_dist(this.player.info.x, this.player.info.y, tx, ty);
            d = Math.min(d, this.flashDistance); // 限制最大闪现距离

            let angle = Math.atan2(ty - this.player.info.y, tx - this.player.info.x);

            // 计算实际落点坐标
            const newX = this.player.info.x + d * Math.cos(angle);
            const newY = this.player.info.y + d * Math.sin(angle);

            // 创建闪现效果
            this.create_flash_effect(angle, d);

            // 在单人游戏模式下，直接在本地应用闪现效果
            if (this.player.gameMap.constructor.name === 'SingleMap') {
                // 限制不要超出地图边界
                const buffer = this.player.info.radius * 2;
                const boundedX = Math.max(buffer, Math.min(this.player.gameMap.width - buffer, newX));
                const boundedY = Math.max(buffer, Math.min(this.player.gameMap.height - buffer, newY));
                
                // 更新玩家位置
                this.player.info.x = boundedX;
                this.player.info.y = boundedY;

                // 重置玩家移动状态
                this.player.move_length = 0;
                this.player.vx = 0;
                this.player.vy = 0;
            }

            // 返回成功信息
            return {
                success: true,
                newX: newX,
                newY: newY,
            };
            
        } catch (error) {
            console.error("闪现技能使用失败:", error);
            return false;
        }
    }

    // 计算两点之间的距离
    get_dist(x1, y1, x2, y2) {
        return Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
    }

    // 创建闪现效果 - 分离出来方便联机时使用
    create_flash_effect(angle, distance) {
        try {
            const startX = this.player.info.x
            const startY = this.player.info.y
            const endX = startX + Math.cos(angle) * distance
            const endY = startY + Math.sin(angle) * distance

            // 创建并添加闪现效果实体
            new FlashEffectEntity(this.player.gameMap, {
                startX: startX,
                startY: startY,
                endX: endX,
                endY: endY,
                radius: this.player.info.radius * 0.5,
                player: this.player,
            })
        } catch (error) {
            console.error("创建闪现效果失败:", error);
        }
    }
}

// 闪现效果实体类
class FlashEffectEntity extends GameObject {
    constructor(gameMap, info) {
        super();
        this.gameMap = gameMap;
        this.info = info;
        this.lifespan = 300; // 效果持续时间(毫秒)
        this.particles = [];
        
        // 检查必要参数
        if (!this.gameMap || !this.info) {
            console.error("创建闪现效果失败: 参数无效");
            this.destroy();
            return;
        }
        
        this.create_particles();
    }

    start() {}

    // 创建粒子效果
    create_particles() {
        try {
            // 在起点和终点之间创建粒子
            const numParticles = 15;
            for (let i = 0; i < numParticles; i++) {
                // 在闪现路径上创建粒子
                const t = i / (numParticles - 1); // 0到1之间的插值因子
                const x = this.info.startX * (1 - t) + this.info.endX * t;
                const y = this.info.startY * (1 - t) + this.info.endY * t;

                // 添加一些随机偏移
                const offsetX = (Math.random() - 0.5) * this.info.radius * 0.5;
                const offsetY = (Math.random() - 0.5) * this.info.radius * 0.5;

                // 生成随机大小和生命周期
                const size = this.info.radius * (0.2 + Math.random() * 0.4);
                const maxLifespan = 200 + Math.random() * 100;

                // 创建粒子
                this.particles.push({
                    x: x + offsetX,
                    y: y + offsetY,
                    size: size,
                    lifespan: maxLifespan,
                    maxLifespan: maxLifespan,
                    alpha: 1.0,
                });
            }
        } catch (error) {
            console.error("创建闪现粒子效果失败:", error);
        }
    }

    update() {
        try {
            // 更新生命周期
            this.lifespan -= this.timeDelta;

            // 如果效果已结束，销毁
            if (isNaN(this.lifespan) || this.lifespan <= 0) {
                this.destroy();
                return;
            }

            // 更新所有粒子
            for (let i = this.particles.length - 1; i >= 0; i--) {
                const particle = this.particles[i];

                // 减少粒子生命周期
                particle.lifespan -= this.timeDelta;

                // 计算透明度
                particle.alpha = particle.lifespan / particle.maxLifespan;

                // 如果粒子生命周期结束，移除
                if (particle.lifespan <= 0) {
                    this.particles.splice(i, 1);
                }
            }

            this.draw();
        } catch (error) {
            console.error("更新闪现效果失败:", error);
            this.destroy();
        }
    }
    
    // 析构函数 - 清理资源
    on_destroy() {
        this.particles = [];
    }

    draw() {
        try {
            // 绘制所有粒子
            for (const particle of this.particles) {
                if (!this.gameMap || !this.gameMap.ctx) continue;
                
                this.gameMap.ctx.beginPath();
                // 确保alpha是有效值
                const alpha = isNaN(particle.alpha) ? 0.5 : particle.alpha;
                this.gameMap.ctx.globalAlpha = alpha;

                // 创建径向渐变
                const gradient = this.gameMap.ctx.createRadialGradient(
                    particle.x,
                    particle.y,
                    0,
                    particle.x,
                    particle.y,
                    particle.size
                );

                gradient.addColorStop(0, `rgba(255, 255, 255, ${alpha})`);
                gradient.addColorStop(0.7, `rgba(200, 220, 255, ${alpha * 0.7})`);
                gradient.addColorStop(1, 'rgba(150, 180, 255, 0)');

                this.gameMap.ctx.fillStyle = gradient;
                this.gameMap.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
                this.gameMap.ctx.fill();
                this.gameMap.ctx.globalAlpha = 1.0;
            }

            // 添加发光效果(连接线)
            if (this.particles.length > 1 && this.gameMap && this.gameMap.ctx) {
                this.gameMap.ctx.beginPath();
                this.gameMap.ctx.moveTo(this.info.startX, this.info.startY);
                this.gameMap.ctx.lineTo(this.info.endX, this.info.endY);
                
                // 确保lifespan是有效值
                const lifespanRatio = isNaN(this.lifespan) ? 0 : this.lifespan / 300;
                const alpha = lifespanRatio * 0.3;
                
                this.gameMap.ctx.strokeStyle = `rgba(200, 220, 255, ${alpha})`;
                this.gameMap.ctx.lineWidth = this.info.radius * 0.2;
                this.gameMap.ctx.stroke();
            }
        } catch (error) {
            console.error("渲染闪现效果失败:", error);
        }
    }
}